from django.core.paginator import Paginator, EmptyPage, Page, PageNotAnInteger
from django.shortcuts import render
from django.views.decorators.http import require_POST, require_http_methods
from datetime import datetime, timedelta

from message.models import Message
from utils.json_to_dict import json_to_dict
from utils.decorator import login_require
from .models import *
from django.shortcuts import redirect
from django.http import JsonResponse, HttpResponse
from django.db.models import Q


def index(request):
    blog_list = Blog.objects.all()

    return render(request, 'bl/index.html', locals())


def xiangqing(request):
    id = request.GET.get('id')
    print('id', id)
    blog = Blog.objects.get_one_object(id=id)
    comments = blog.comment_set.all()
    # print(blog.title)
    return render(request, 'bl/xiangqing.html', locals())


@require_http_methods(['GET', 'POST'])
def register(request):
    if request.method == 'GET':
        return render(request, 'bl/zhuce.html')
    else:
        data = json_to_dict(request)
        username = data['username']
        password = data['password']
        email = data['email']
        AccountInfo.objects.add_account(username=username, password=password, email=email)

        return redirect('bl/login/')


def login(request):
    if 'username' in request.COOKIES:
        username = request.COOKIES['username']
    else:
        username = ''
    return render(request, "bl/login.html", {'username': username})


def liuyan(request):
    username = request.session['username']
    user_info = AccountInfo.objects.get_one_object(username=username)
    try:
        messages = user_info.message_set.all()
    except Exception as e:
        print(str(e))
    return render(request, 'bl/liuyan.html', locals())
    # return render(request, "bl/liuyan.html")


@require_POST
def login_check(request):
    data = json_to_dict(request)
    username = data['username']
    password = data['password']
    # username = request.POST.get('username')
    # password = request.POST.get('password')
    obj = AccountInfo.objects.handle_one_account(username=username, password=password)
    if obj:
        # remember = data['remember']
        remember = data.get('remember')
        jsp = JsonResponse({'res': 1, })
        if remember == 'true':
            jsp.set_cookie('username', username, expires=datetime.now() + timedelta(days=14))
        request.session['username'] = username
        request.session['is_login'] = True
        request.session['account_id'] = obj.id
    else:
        jsp = JsonResponse({'res': 0})
    return jsp


def logout(request):
    request.session.flush()
    return redirect('/')


@login_require
def set_password(request):
    return render(request, 'bl/pass.html')


def change_password(request):
    old_password = request.POST.get('mpass')
    password1 = request.POST.get('newpass')
    print(11, old_password, 22, password1)
    password2 = request.POST.get('renewpass')
    username = request.session['username']
    print('username', username)
    user_info = AccountInfo.objects.handle_one_account(username=username, password=old_password)
    if user_info is not None:
        if password1 == password2:
            user_info.password = get_hash(password2)
            user_info.save()
            # return JsonResponse({'code': 0, 'msg': '修改成功请返回登陆！'})
            return render(request, "bl/back_login.html")
        return JsonResponse({'code': 1, 'msg': '两次密码输入不一致！'})
    return JsonResponse({'code': 2, 'msg': '旧密码输入错误！'})


# 后台内容


def back_index(request):
    return render(request, 'bl/back_index.html', context={})


def back_login(request):
    if 'username' in request.COOKIES:
        username = request.COOKIES['username']
    else:
        username = ''
    return render(request, "bl/back_login.html", {'username': username})


@login_require
def page(request):
    return render(request, 'bl/page.html', context={})


# 添加博客
@login_require
@require_POST
def add_blog(request):
    title = request.POST.get('title')
    # img = request.POST.get('img')
    print(11, title, )
    content = request.POST.get('content')
    username = request.session['username']
    print('username', username)
    user_info = AccountInfo.objects.get_one_object(username=username)

    blog = Blog.objects.add_blog(title, content, user_info.id)
    blog_id = blog.id
    print(blog_id)
    request.session['bolg'] = blog_id
    print(blog_id)
    return redirect('../')


def list_blog(request):
    blog_list = Blog.objects.all()
    paginator = Paginator(blog_list, 2)
    page = request.GET.get('page', 1)
    # 把当前页面转化为整数类型
    currentPage = int(page)

    print("page", page)
    print(paginator.page_range)
    try:
        blog_list = paginator.page(page)  # 获取当前页码的记录
    except PageNotAnInteger:
        blog_list = paginator.page(1)  # 如果用户输入的页码不是整数时,显示第1页的内容
    except EmptyPage:
        blog_list = paginator.page(paginator.num_pages)  # 如果用户输入的页数不在系统的页码列表中时,显示最后一页的内容

    # return render(request, "myuseradmin/list.html", locals())

    return render(request, 'bl/list.html', locals())


# 博客详情页    现在缺少详情页,没用后面用的xingqing
@require_http_methods(['GET', 'POST'])
def blog_detail(request, pk):
    blog = Blog.objects.get_one_object(id=pk)
    return render(request, 'bl/detail.html', {'blog': blog})


def delete_blog(request):
    data = json_to_dict(request)
    id = data['id']
    print('id', id)
    obj = Blog.objects.get_one_object(id=id)
    if obj:
        obj.delete()
        return JsonResponse({'res': 1})
    else:
        return JsonResponse({'res': 0})

    # @check_login
    # def editCon(request):
    title = request.POST['title']
    con = request.POST['con']
    author = request.POST['author']
    Content.objects.update(title=title, con=con, author=author)
    return HttpResponse("修改内容")


def list_edit_blog(request, id):
    blog = Blog.objects.get(id=id)
    return render(request, "bl/edit.html", {'blog': blog})


def edit_blog(request):
    title = request.POST['title']
    content = request.POST['content']
    id = request.POST['id']
    Blog.objects.filter(id=id).update(title=title, content=content)
    # return HttpResponse("修改内容")
    return redirect('/blog/blog_list/')


@login_require
def search(request):
    kw = request.POST.get('kw')
    blogs = Blog.objects.filter(Q(title__contains=kw) | Q(content__contains=kw))
    return render(request, 'bl/list.html', locals())


def blog_tags(request):
    b = Blog.objects.get_one_object(id=1)
    tags = b.tags.all()
    # tags = Blog().tags.all()   # 多对多查询出标签
    for tag in tags:
        print(tag)
    return render(request, {'tags': tags})


def tag_blogs(request):
    blogs = Tag().blog_set.all()

    return render(request, {'blogs': blogs})
